﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;

namespace TVDBDownloader
{
    class FanArtTVDownloader
    {
        internal TvdbLib.Data.TvdbBanner DownloadBanner(int tvdbID, TVDBDownloader.Downloader.BannerType type)
        {
            string bannerType = type.ToString();
            if (type == Downloader.BannerType.Logo)
                bannerType = "clearlogo";
            WebRequest request = WebRequest.Create("http://fanart.tv/api/fanart.php?id=" + tvdbID + "&type=" + bannerType.ToLower());
            WebResponse response = request.GetResponse();
            Stream receiveStream = response.GetResponseStream();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

            string result = readStream.ReadToEnd();
            Regex regex = new Regex(type.ToString() + " url=\"(.*?)\"/>", RegexOptions.IgnoreCase);
            Match match = regex.Match(result);
            TvdbLib.Data.TvdbBanner banner = new TvdbLib.Data.TvdbBanner();
            if (match != null)
            {
                banner.BannerPath = match.Groups[1].Value;
                banner.Id = -1;
            }

            return banner;
        }
    }
}
